from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from .models import City, IDC, Host, HostStat
from .serializers import CitySerializer, IDCSerializer, HostSerializer, HostStatSerializer
import subprocess
import platform


class CityViewSet(viewsets.ModelViewSet):
    queryset = City.objects.all()
    serializer_class = CitySerializer


class IDCViewSet(viewsets.ModelViewSet):
    queryset = IDC.objects.select_related('city')
    serializer_class = IDCSerializer


class HostViewSet(viewsets.ModelViewSet):
    queryset = Host.objects.select_related('idc', 'idc__city')
    serializer_class = HostSerializer

    @action(detail=True, methods=['get'])
    def ping(self, request, pk=None):
        host = self.get_object()

        param = '-n' if platform.system().lower() == 'windows' else '-c'
        command = ['ping', param, '3', host.ip_address]

        try:
            output = subprocess.check_output(
                command,
                stderr=subprocess.STDOUT,
                universal_newlines=True,
                timeout=5
            )
            return Response({
                'status': 'reachable',
                'output': output
            })
        except subprocess.CalledProcessError:
            return Response({
                'status': 'unreachable',
                'message': f'Host {host.ip_address} is not reachable'
            }, status=status.HTTP_400_BAD_REQUEST)
        except subprocess.TimeoutExpired:
            return Response({
                'status': 'timeout',
                'message': f'Ping to {host.ip_address} timed out'
            }, status=status.HTTP_408_REQUEST_TIMEOUT)


class HostStatViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = HostStat.objects.select_related('city', 'idc')
    serializer_class = HostStatSerializer
    filterset_fields = ['city', 'idc', 'stat_date']
